package com.jia.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.res.AssetManager;
import android.content.res.Resources;

import com.jia.R;

/**
 * [文本文件操作类] <br>
 *
 * @author [jia.xiuya] <br>
 * @version 1.0 <br>
 * @taskId br>
 * @CreateDate 13-7-31 <br>
 * @see com.jia.utils <br>
 * @since V7.3<br>
 */
public final class TextFileUtil {

    public static String getStringFromRawFile(Activity activity)
            throws IOException {
        Resources r = activity.getResources();
        InputStream is = r.openRawResource(R.raw.test_text);
        String myText = convertStreamToString(is);
        is.close();
        return myText;
    }

    /**
     * 使用另一种方法读取Text文件
     * @param activity
     * @return
     * @throws IOException
     */
    public static String getStringFromAssetFile(Activity activity) throws IOException {
        AssetManager am = activity.getAssets();
        InputStream is = am.open("test_text.text");
        String s = convertStreamToString(is);
        is.close();
        return s;
    }

    private static String convertStreamToString(InputStream is)
            throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i = is.read();
        while (i != -1) {
            baos.write(i);
            i = is.read();
        }
        return baos.toString();
    }
}
